package com.bocloud.cmp.service.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @Title: HexUtils.java
 * @Description: 10进制16进制转换
 * @author lkx
 * @date 2016年11月28日 下午2:26:23
 * @version V1.0
 */
public class HexUtils {

	private static Logger logger = LoggerFactory.getLogger(HexUtils.class);

	public static String stringToHexString(String s) {
		String str = "";
		for (int i = 0; i < s.length(); i++) {
			int ch = (int) s.charAt(i);
			String s4 = Integer.toHexString(ch);
			str = str + s4;
		}
		return str;
	}

	/**
	 * 16进制字符串转换为字符串
	 * 
	 * @param s
	 * @return
	 */
	public static String hexStringToString(String s) {
		if (s == null || s.equals("")) {
			return null;
		}
		String bak = s;
		s = s.replaceAll(":", "").replace(" ", "");
		byte[] baKeyword = new byte[s.length() / 2];
		for (int i = 0; i < baKeyword.length; i++) {
			try {
				baKeyword[i] = (byte) (0xff & Integer.parseInt(s.substring(i * 2, i * 2 + 2), 16));
			} catch (Exception e) {
				logger.error("", e);
				return bak;
			}
		}
		try {
			s = new String(baKeyword, "gbk");
		} catch (Exception e) {
			logger.error("", e);
			return bak;
		}
		return s;
	}
}
